"""
邮件相关的Pydantic模型
"""

from typing import Optional, List, Dict, Any
from datetime import datetime
from pydantic import BaseModel, EmailStr, Field, validator
from enum import Enum

from app.models.email_message import EmailStatus, EmailType, EmailPriority


class EmailStatusEnum(str, Enum):
    """邮件状态枚举"""
    PENDING = "pending"
    SENDING = "sending"
    SENT = "sent"
    FAILED = "failed"
    DELIVERED = "delivered"
    READ = "read"


class EmailTypeEnum(str, Enum):
    """邮件类型枚举"""
    USER_MESSAGE = "user_message"
    NOTIFICATION = "notification"
    WELCOME = "welcome"
    PASSWORD_RESET = "password_reset"
    VERIFICATION = "verification"
    SYSTEM_ALERT = "system_alert"


class EmailPriorityEnum(int, Enum):
    """邮件优先级枚举"""
    LOW = 1
    NORMAL = 2
    HIGH = 3
    URGENT = 4


# 请求模型
class EmailSendRequest(BaseModel):
    """发送邮件请求"""
    recipient_email: EmailStr = Field(..., description="收件人邮箱")
    recipient_name: Optional[str] = Field(None, description="收件人姓名")
    subject: str = Field(..., min_length=1, max_length=500, description="邮件主题")
    body_text: Optional[str] = Field(None, description="纯文本内容")
    body_html: Optional[str] = Field(None, description="HTML内容")
    priority: EmailPriorityEnum = Field(EmailPriorityEnum.NORMAL, description="邮件优先级")
    
    @validator('body_text', 'body_html')
    def validate_body_content(cls, v, values):
        """验证邮件内容"""
        if not v and not values.get('body_html') and not values.get('body_text'):
            raise ValueError('邮件必须包含文本内容或HTML内容')
        return v


class EmailTemplateRequest(BaseModel):
    """使用模板发送邮件请求"""
    recipient_email: EmailStr = Field(..., description="收件人邮箱")
    recipient_name: Optional[str] = Field(None, description="收件人姓名")
    template_name: str = Field(..., description="模板名称")
    template_data: Dict[str, Any] = Field(default_factory=dict, description="模板数据")
    priority: EmailPriorityEnum = Field(EmailPriorityEnum.NORMAL, description="邮件优先级")


class EmailBatchRequest(BaseModel):
    """批量发送邮件请求"""
    recipients: List[Dict[str, str]] = Field(..., description="收件人列表")
    subject: str = Field(..., min_length=1, max_length=500, description="邮件主题")
    body_text: Optional[str] = Field(None, description="纯文本内容")
    body_html: Optional[str] = Field(None, description="HTML内容")
    template_name: Optional[str] = Field(None, description="模板名称")
    template_data: Dict[str, Any] = Field(default_factory=dict, description="模板数据")
    priority: EmailPriorityEnum = Field(EmailPriorityEnum.NORMAL, description="邮件优先级")
    scheduled_at: Optional[datetime] = Field(None, description="计划发送时间")
    
    @validator('recipients')
    def validate_recipients(cls, v):
        """验证收件人列表"""
        if not v:
            raise ValueError('收件人列表不能为空')
        
        for recipient in v:
            if 'email' not in recipient:
                raise ValueError('每个收件人必须包含email字段')
        
        return v


class UserMessageRequest(BaseModel):
    """用户间消息请求"""
    recipient_id: int = Field(..., description="收件人用户ID")
    subject: str = Field(..., min_length=1, max_length=500, description="消息主题")
    message: str = Field(..., min_length=1, description="消息内容")
    priority: EmailPriorityEnum = Field(EmailPriorityEnum.NORMAL, description="消息优先级")


# 响应模型
class EmailMessageResponse(BaseModel):
    """邮件消息响应"""
    id: int
    sender_email: str
    sender_name: Optional[str]
    recipient_email: str
    recipient_name: Optional[str]
    subject: str
    email_type: EmailTypeEnum
    priority: EmailPriorityEnum
    status: EmailStatusEnum
    sent_at: Optional[datetime]
    delivered_at: Optional[datetime]
    read_at: Optional[datetime]
    failed_reason: Optional[str]
    retry_count: int
    created_at: datetime
    updated_at: Optional[datetime]
    
    class Config:
        from_attributes = True


class EmailMessageDetail(EmailMessageResponse):
    """邮件消息详情"""
    body_text: Optional[str]
    body_html: Optional[str]
    template_name: Optional[str]
    is_system_email: bool
    can_retry: bool


class EmailSendResponse(BaseModel):
    """发送邮件响应"""
    success: bool
    message: str
    email_id: Optional[int] = None
    request_id: Optional[str] = None


class EmailBatchResponse(BaseModel):
    """批量发送邮件响应"""
    success: bool
    message: str
    batch_id: str
    total_emails: int
    queued_emails: int
    failed_emails: int
    email_ids: List[int]


class EmailStatsResponse(BaseModel):
    """邮件统计响应"""
    total_sent: int
    total_pending: int
    total_failed: int
    total_delivered: int
    success_rate: float
    recent_emails: List[EmailMessageResponse]


# 模板相关模型
class EmailTemplateCreate(BaseModel):
    """创建邮件模板"""
    name: str = Field(..., min_length=1, max_length=100, description="模板名称")
    display_name: str = Field(..., min_length=1, max_length=200, description="显示名称")
    description: Optional[str] = Field(None, description="模板描述")
    subject_template: str = Field(..., min_length=1, max_length=500, description="主题模板")
    body_template: str = Field(..., min_length=1, description="内容模板")
    email_type: EmailTypeEnum = Field(..., description="邮件类型")
    variables: Optional[Dict[str, str]] = Field(None, description="模板变量说明")


class EmailTemplateUpdate(BaseModel):
    """更新邮件模板"""
    display_name: Optional[str] = Field(None, min_length=1, max_length=200, description="显示名称")
    description: Optional[str] = Field(None, description="模板描述")
    subject_template: Optional[str] = Field(None, min_length=1, max_length=500, description="主题模板")
    body_template: Optional[str] = Field(None, min_length=1, description="内容模板")
    is_active: Optional[bool] = Field(None, description="是否激活")
    variables: Optional[Dict[str, str]] = Field(None, description="模板变量说明")


class EmailTemplateResponse(BaseModel):
    """邮件模板响应"""
    id: int
    name: str
    display_name: str
    description: Optional[str]
    subject_template: str
    body_template: str
    email_type: EmailTypeEnum
    is_active: bool
    is_system: bool
    variables: Optional[Dict[str, str]]
    created_at: datetime
    updated_at: Optional[datetime]
    
    class Config:
        from_attributes = True


# 查询参数模型
class EmailListParams(BaseModel):
    """邮件列表查询参数"""
    page: int = Field(1, ge=1, description="页码")
    size: int = Field(20, ge=1, le=100, description="每页大小")
    status: Optional[EmailStatusEnum] = Field(None, description="邮件状态")
    email_type: Optional[EmailTypeEnum] = Field(None, description="邮件类型")
    sender_email: Optional[str] = Field(None, description="发件人邮箱")
    recipient_email: Optional[str] = Field(None, description="收件人邮箱")
    date_from: Optional[datetime] = Field(None, description="开始日期")
    date_to: Optional[datetime] = Field(None, description="结束日期")
    search: Optional[str] = Field(None, description="搜索关键词（主题）")